package com.budwk.app.sqfwV2.service.dayingRoad;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuRedRecordPdfDTO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuWhiteRecordPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.RedWhite;
import com.budwk.app.sqfwV2.enums.RedWhitePdf;
import com.budwk.app.sqfwV2.generator.dayingRoadPdf.rw.*;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.createConvergePdfAndUpload;
import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.generateWordDocument;

/**
 * 本代码由代码生成器生成，版本号1.0
 */
@IocBean
@Slf4j
public class RedWhiteRecordPdfService extends CompleteFlowCommonPdfService {

    @Inject
    SysUserService sysUserService;
    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;
    @Inject
    private SummarySafetyService summarySafetyService;

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        log.info("大营路红白事备案：{}", JSONUtil.toJsonStr(paramForController));

        DaYingLuWhiteRecordPdfDTO pdfDTO = null;
        try {
            pdfDTO = JSONUtil.toBean(paramForController.getCompleteFlowDataDTO().getFormSummary().getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        } catch (NumberFormatException e) {
            throw new ServiceException("请填写正确的数据格式：" + e.getMessage());
        }

        TemplateCodeUpdateDTO dto = new TemplateCodeUpdateDTO();

        Sqfw_formSummary_new formSummary = paramForController.getCompleteFlowDataDTO().getFormSummary();
        formSummary.setFillDate(pdfDTO.getDate());
        dto.setFormSummary(formSummary);
        // 创建任务
        summarySafetyCommponent.createOneTask(dto, null, getSummaryType());
        // 创建pdf
        super.createPdfAndMsg(paramForController);
    }

    /**
     * 获取数据
     * @return
     */
    public Result<?> list(Integer pageNo, Integer pageSize, String type, String fillDate, String sort) {
        SummaryQueryReqVo dto = new SummaryQueryReqVo();
        dto.setPageNo(pageNo);
        dto.setPageSize(pageSize);
        dto.setSort(sort);
        dto.setFillDate(fillDate);
        dto.setFillType(getSummaryType());
        if (StringUtils.isNotBlank(type)) {
            SqlExpressionGroup sql = new SqlExpressionGroup();
            sql.and("param_data ->>'celebratoryEvents'","=", type);
            dto.setSqlExpressionGroup(sql);
        }
        return summarySafetyService.listSummaryByPage(dto);
    }

    public void update(TemplateCodeUpdateDTO dto) {
        log.info("大营路红白事备案更新：{}", JSONUtil.toJsonStr(dto));
        DaYingLuWhiteRecordPdfDTO pdfDTO = null;
        try {
            pdfDTO = JSONUtil.toBean(dto.getFormSummary().getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        } catch (NumberFormatException e) {
            throw new ServiceException("请填写正确的数据格式：" + e.getMessage());
        }
        dto.getFormSummary().setFillDate(pdfDTO.getDate());
        sqfwFormsummaryNewService.updateIgnoreNull(dto.getFormSummary());
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(dto.getFormSummary().getId());
        CompleteFlowPdfParamForController paramForController = new CompleteFlowPdfParamForController();
        CompleteFlowTemplateCodeUpdateDTO updateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        updateDTO.setFormSummary(formSummaryNew);
        paramForController.setCompleteFlowDataDTO(updateDTO);
        paramForController.setCompleteFlowId(formSummaryNew.getSqfwFlowId());
        paramForController.setUserId(SecurityUtil.getUserId());
        super.reCreatePdfAndMsg(paramForController);
    }

    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String jasonStr) {
        DaYingLuWhiteRecordPdfDTO pdfDTO = JSONUtil.toBean(jasonStr, DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        if (RedWhite.RED.getName().equals(celebratoryEvents)) {
            return JSONObject.parseObject(jasonStr, DaYingLuRedRecordPdfDTO.class);
        } else {
            return JSONObject.parseObject(jasonStr, DaYingLuWhiteRecordPdfDTO.class);
        }
    }

    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("signature", pdfGenerateParam.getCreateUserCommonParam().getCreateUserSigUrl());
        pdfGenerateParam.setCustomerParamMap(map);
    }

    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        DaYingLuWhiteRecordPdfDTO pdfDTO = BeanUtil.toBean(pdfGenerateParam.getAbstractCustomerPdfCreateField(), DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        if (RedWhite.RED.getName().equals(celebratoryEvents)) {
            generatorList.add(new RedHandleCateringRecordsPdfGenerator());
            generatorList.add(new RedAndWhiteCivilizedAndThriftyGenerator());
            generatorList.add(new RedAndWhiteSecurityGenerator());
        } else {
            generatorList.add(new WhiteHandleCateringRecordsPdfGenerator());
            generatorList.add(new RedAndWhiteCivilizedAndThriftyGenerator());
            generatorList.add(new RedAndWhiteSecurityGenerator());
            generatorList.add(new RedAndWhiteDiscourageGenerator());
        }
        return generatorList;
    }

    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        DaYingLuWhiteRecordPdfDTO pdfDTO = BeanUtil.toBean(pdfGenerateParam.getAbstractCustomerPdfCreateField(), DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        return RedWhite.RED.getName().equals(celebratoryEvents) ? "婚事办理酒席备案表" : "丧事办理酒席备案表";
    }

    @Override
    protected String getSummaryType() {
        return SqfwFormSummaryConstants.red_white_record;
    }

    /**
     * 红白事pdf合集下载
     * @return
     */
    public List<GenerateExcelUrlVO> downPdfList(DownExcelLedgerReqVo reqVo) {

        List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
        if (reqVo.isDownTemplate()) {
            ExcelCreateConfig config = new ExcelCreateConfig();
            config.setFileIdentity(reqVo.getFileCode());
            config.setOnlyGenerateTemplateFlag(true);
            excelConfigList.add(config);
        } else {
            if (reqVo.isCheckData()) {
                for (RedWhitePdf pdf : RedWhitePdf.values()) {
                    ExcelCreateConfig config = new ExcelCreateConfig();
                    config.setFileIdentity(pdf.getCode());
                    config.setCreateExcelFileFlag(false);
                    excelConfigList.add(config);
                }
            } else {
                ExcelCreateConfig config = new ExcelCreateConfig();
                config.setFileIdentity(reqVo.getFileCode());
                config.setCreateExcelFileFlag(true);
                excelConfigList.add(config);
            }
        }


        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();

        for (ExcelCreateConfig config : excelConfigList) {

            // 模板下载
            if (config.getOnlyGenerateTemplateFlag()) {
                GenerateExcelUrlVO urlVO = new GenerateExcelUrlVO();
                String url = downWordTemplate(config);
                urlVO.setExcelUrl(url);
                generateExcelUrlVOS.add(urlVO);
                return generateExcelUrlVOS;
            }

            // 数据下载
            String fileName;
            String celebratoryEvents;
            if (RedWhitePdf.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
                fileName = RedWhitePdf.RED_TRACKING_REPORT.getName();
                celebratoryEvents = RedWhite.RED.getName();
            } else {
                fileName = RedWhitePdf.WHITE_INFORMATION_STATISTICS.getName();
                celebratoryEvents = RedWhite.WHITE.getName();
            }
            String sql = "select sc.resource_path from shequ.sqfw_completeflow sc left join shequ.sqfw_form_summary_new sfsn " +
                    "on sc.id = sfsn.sqfw_flow_id where " +
                    "sfsn.param_data->>'celebratoryEvents' = '"+ celebratoryEvents +"' and sc.user_id ='"+SecurityUtil.getUserId()+"' " +
                    "and sc.resource_path != 'error' and sc.resource_path != 'creating' ";
            if (StringUtils.isNotBlank(reqVo.getFillStartDate())) {
                sql += "and sfsn.fill_date >= '"+reqVo.getFillStartDate()+"' ";
            }
            if (StringUtils.isNotBlank(reqVo.getFillEndDate())) {
                sql += "and sfsn.fill_date <= '"+reqVo.getFillEndDate()+" 23:59:59' ";
            }
            sql += "order by sc.create_date asc";
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.listEntity(Sqls.create(sql));

            GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
            generateExcelUrlVO.setFileIdentity(config.getFileIdentity());

            if (completeFlowList != null && completeFlowList.size() > 0) {
                generateExcelUrlVO.setCreateConditionFlag(true);
            } else {
                generateExcelUrlVO.setCreateConditionFlag(false);
            }

            // 数据检测
            if (!config.getCreateExcelFileFlag() || completeFlowList == null || completeFlowList.size() == 0) {
                generateExcelUrlVOS.add(generateExcelUrlVO);
                continue;
            }

            List<String> pdfList = completeFlowList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());

            try {
                String url = createConvergePdfAndUpload(pdfList, fileName);
                generateExcelUrlVO.setExcelUrl(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            generateExcelUrlVOS.add(generateExcelUrlVO);
        }

        return generateExcelUrlVOS;
    }

    /**
     * 下载word模板
     * @param config
     * @return
     */
    private String downWordTemplate(ExcelCreateConfig config) {
        String fileName = "";

        Map<String, Object> dataMap = JSONUtil.parseObj(new Sqfw_formSummary_new(), false);
        List<NiceXWPFDocument> xwpfDocumentList = new ArrayList<>();

        if (RedWhitePdf.WHITE_INFORMATION_STATISTICS.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.WHITE_INFORMATION_STATISTICS.getName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuWhiteRecordPdfDTO(), false));

            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new WhiteHandleCateringRecordsPdfGenerator().getTemplatePath(null)));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteCivilizedAndThriftyGenerator().getTemplatePath(null)));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteSecurityGenerator().getTemplatePath(null)));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteDiscourageGenerator().getTemplatePath(null)));
        }
        if (RedWhitePdf.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.RED_TRACKING_REPORT.getName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuRedRecordPdfDTO(), false));

            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedHandleCateringRecordsPdfGenerator().getTemplatePath(null)));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteCivilizedAndThriftyGenerator().getTemplatePath(null)));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteSecurityGenerator().getTemplatePath(null)));

        }

        GenerateWordAndPdfUrlVO vo = CommonFormOfficeUtils.wordUpload(xwpfDocumentList, fileName.replace("合集", "模板"));
        return vo.getWordUrl();
    }

    /**
     * 生成单个word
     * @param dataMap
     * @param templateName
     * @return
     */
    private NiceXWPFDocument getNiceXWPFDocument(Map<String, Object> dataMap, String templateName) {
        for (String key : dataMap.keySet()) {
            dataMap.put(key, "");
        }
        dataMap.put("yyyy", "");
        dataMap.put("mm", "");
        dataMap.put("dd", "");
        dataMap.put("hh", "");
        dataMap.put("checkedUnitLeaders", new ArrayList<>());
        dataMap.put("signatures", new ArrayList<>());
        dataMap.put("visitPictures", new ArrayList<>());
        dataMap.put("fillDateStr", "");
        dataMap.put("title", "XX");
        dataMap.put("boardOfGovernors", "");

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, null, templateName);
        return xwpfTemplate.getXWPFDocument();
    }
}
